<?php
namespace App\Http\Controllers\Back;

use App\Http\Controllers\BaseController;
use DB;
use App\Libraries\newsmsapi;
use App\Libraries\Captcha;
use Config;
use App\Http\Models\User;
use Illuminate\Http\Request;

/**

 */
class UserController extends BaseController
{
    /**
     * 请求参数
     */
    private $request;

    /**
     * 验证码有效期
     */
    private $captcha_expire_time = 180;

    public function __construct()
    {
        $this->request = $this->requestAll();
        parent::__construct();
    }

    public function  test()
    {

    }
    //验证登录
    public function checkLogin(){
        $login_session = session(config('session.pass'));

        if(json_decode($login_session)){
            return true;
        }else{
            return false;
        }
    }

    //退出登录
    public function logout(Request $request){

       $request->session()->invalidate();
        return redirect('back/showLogin');

    }

    //显示登录页面
    public function showLogin(){
         
            return view('back.login');
    }

    //登录
    public function login() {
        $input = $this->request;
        //图片验证验证
        $code = DB::table('token')->where('key',$input['csrf_token'])
            ->where('val',$input['vercode'])->first();
        if(empty($code)){
            return '验证码错误！';
        }

        $pass = md5(md5($input['user_pass']).config('session.pass'));
        $res  = DB::table('user')->where(['user_phone'=>$input['user_phone'],'user_pass'=>$pass,'is_del'=>0,'user_type'=>20])->first();

        $roleMenuId = DB::table('role')->where(['role_id'=>$res['user_role_id']])
            ->value('role_menu_id');

        //session 数据
        $data=[
            'user_id'=>$res['user_id'],
            'user_type'=>$res['user_type'],
            'user_role_id'=>$res['user_role_id'],
            'user_phone'=>$res['user_phone'],
            'user_email'=>$res['user_email'],
            'role_menu_id'=>$roleMenuId,
        ];

        if(!empty($res)){
            session([config('session.pass')=>json_encode($data)]);

            return redirect('/back/index');
        }else{
            return '账号或密码错误！';
           // return redirect('/back/showLogin');
        }
   }
    //获取图形验证码接口

    public function getImgCode()
    {
        $csrfToken = isset($this->request['csrfToken'])?$this->request['csrfToken']:0;
        $base64 = isset($this->request['base64']) ? intval($this->request['base64']) : 0 ;
        $objCaptcha = new Captcha(80, 40, 4);
        $objCaptcha->buildAndExportImage();
        $code = $objCaptcha->getCaptchaCode();
        if (!empty($code) && !empty($csrfToken)) {
            $key =  $csrfToken;
            $data =[
                'key'=>$key,
                'val'=>$code,
                'add_time'=>date('Y-m-d H:i:s')
            ];

            $re = DB::table('token')->where('key',$key)->first();
            if(!empty($re)){
                DB::table('token')->where('key',$key)->update(['val'=>$code]);
            }else{
                $rs = DB::table('token')->insertGetId($data);
            }
        }
        if(!empty($base64)) {
            $base64Encode = $objCaptcha->base64Image();
            $this->jsonResult(true, ['base64Encode' => $base64Encode]);
        }else {
            $objCaptcha->outputImage();
        }
        exit;
    }

    //验证图片验证码接口
    public function verifyImageCode()
    {
        $imageCode = $this->request['code'];
        $csrfToken = $this->request['csrfToken'];

        if (!empty($imageCode)) {
            $sysCode =  DB::table('token')->where('key',Config::get('api.imgcode'). ':'. $csrfToken)->first();

            if (strtolower($sysCode['val']) != strtolower($imageCode)) {
                //错误
                $this->jsonResult(0);
            }
            $this->jsonResult(1);
        }
        //为空
        $this->jsonResult(0);
    }

    //显示后台用户
    public function showUser(){
        $userList = DB::table('user')
            ->select('user.*','role.role_name')
            ->leftJoin('role','user.user_role_id','=','role.role_id')
            ->where(['user.user_type'=>20,'user.user_status'=>0])
            ->get()->toArray();

//        p($userList);
        return view('power.showuser',[
            'userList'=>$userList
        ]);
    }

    public function showUserAdd(){

        $roleList=DB::table('role')->select('role_id','role_name')
            ->where('status',0 )->get()->toArray();

        return view('power.showuseradd',[
            'roleList'=>$roleList
        ]);
    }

    public function userAdd(){
        $request = $this->request;
        $pass = md5(md5($request['user_pass']).config('session.pass'));


        $data = [
            'user_type'=>20,//后台用户
            'user_phone'=>$request['user_phone'],
            'user_pass'=>$pass,
            'user_role_id'=>$request['user_role_id']

        ];
        $res = DB::table('user')->insert($data);
        return redirect('power/showuser');

    }

    public function showUserEdit(){


        return view('power.showuseredit',[

        ]);
    }

    public function userEdit(){


    }

    //显示修改密码
    public function showEditPass(){

        $adminInfo = $this->getAdminInfo();


        return view('power.editpass',[
            'adminInfo'=>$adminInfo
        ]);
    }

    //修改密码
    public function editPass(){
        $request = $this->request;
        $pass = md5(md5($request['user_pass']).config('session.pass'));
        $rs = DB::table('user')->where('user_phone',$request['user_phone'])->update(['user_pass'=>$pass]);

        session([config('session.pass')=>'']);
        return redirect('back/showLogin');
    }
}